import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index.js'

const Home = () => import('@/views/home/index.vue')
const Login = () => import('@/views/login/index.vue')
const Video = () => import('@/views/video/index.vue')
const Question = () => import('@/views/question/index.vue')
const Article = () => import('@/views/article/index.vue')
const User = () => import('@/views/user/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const Chat = () => import('@/views/user/chat.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/', alias: '/home', components: { default: Home, bottom: Tabbar } },
  { path: '/video', components: { default: Video, bottom: Tabbar } },
  {
    path: '/question',
    components: { default: Question, bottom: Tabbar },
    meta: { needLogin: true } // 需要登录才能访问,
  },
  { path: '/article/:id', component: Article, name: 'article' },
  {
    path: '/user',
    components: { default: User, bottom: Tabbar },
    meta: { needLogin: true } // 需要登录才能访问
  },
  {
    path: '/user/profile',
    component: Profile,
    meta: { needLogin: true } // 需要登录才能访问,
  },
  {
    path: '/user/chat',
    component: Chat,
    meta: { needLogin: true } // 需要登录才能访问,
  }
]

const router = new VueRouter({
  routes
})
//前置导航守卫
// 设置白名单
const whitePath = ['/user', '/user/profile', '/user/chat']
router.beforeEach((to, from, next) => {
  // 判断浏览器是否有token
  if (store.state.user.token) {
    next()
  } else {
    // 路由元验证
    if (to.meta.needLogin) {
      next('/login?redirect=' + to.fullPath)
    } else {
      next()
    }
    // token失效时自动跳转到登录页
    // if (to.path === '/login') {
    //   next()
    // } else {
    //   next('/login')
    // }
  }
})
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}
export default router
